package com.hcloud.libupload.comom

import android.util.Log
import com.hcloud.libupload.callback.ICreateTaskCallback
import com.hcloud.libupload.request.UploadRequest
import com.hcloud.libupload.task.PutUploadTask
import com.hcloud.libupload.task.ResumeUploadTask
import java.util.concurrent.PriorityBlockingQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit

open class UploadClient : IUpload {

    private val config = UploadLib.instance().uploadConfig
    private val max_thread_size = config.maxUploadTaskSize
    private val max_queue_size = config.maxQueueSize

    private val taskPools by lazy {
        ThreadPoolExecutor(
            max_thread_size,
            max_thread_size,
            3,
            TimeUnit.SECONDS,
            PriorityBlockingQueue<Runnable>(max_queue_size)
        )
    }

    private var priority = 0


    override fun upload(uploadRequest: UploadRequest, iCreateTaskCallback: ICreateTaskCallback) {

        Log.i(
            "upload-sdk",
            "upload-----${uploadRequest.uploadTask == null}---${uploadRequest.uploadTask is ResumeUploadTask} sdkType: ${config.sdkType}"
        )

        if (uploadRequest.uploadTask == null) {
            val taskControl = TaskControl(taskPools)
            val task =  if (config.sdkType == 0){
                ResumeUploadTask(uploadRequest, taskControl, iCreateTaskCallback)
            } else{
                PutUploadTask(uploadRequest, taskControl, iCreateTaskCallback)
            }
            uploadRequest.uploadTask = task
            task.priority = priority
            priority++
        }

        taskPools.execute(uploadRequest.uploadTask)
    }
}